<?php

namespace App\Services\Oauth;

use App\Core\Utils\TwHelper\CommFunction;
use App\Core\Utils\TwHelper\Environment;
use App\Exceptions\Response\Service\ServiceCode;
use App\Exceptions\Response\Service\ServiceException;
use App\Models\Oauth\SendCodeModel;
use App\Models\Club\MemberModel;
use App\Models\Oauth\UserModel;
use App\Core\Utils\TwHelper\VerificationCode;
use App\Models\Oauth\UserProfileModel;
use TencentYun\Sms\SDK\SmsService;
use App\Models\Oauth\DistrictModel;
use App\Core\Utils\Wechat\WechatUserService;
use App\Core\Utils\Wechat\WechatConfig;
use App\Models\Oauth\UserWeiXinModel;
use App\Models\Oauth\WeiXinUserModel;

class RegistService
{
    protected $username;
    protected $mobile;
    protected $password;
    protected $code;

    public function __construct($username = '', $mobile = '', $password = '', $code = '')
    {
        $this->username = $username;
        $this->mobile = $mobile;
        $this->password = $password;
        $this->code = $code;
    }

    /**
     * 验证用户名
     */
    public function checkUserName()
    {
        if (!$this->username) {
            throw new ServiceException(ServiceCode::SERVICE_PARAM_INVALID, '', []);
        }
        $length = strlen($this->username);
        if ($length < 3 || $length > 15) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_USERNAME_LENGTH_IS_WRONG, '', []);
        }
        if (preg_match('/^\d+$/', $this->username)) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_USERNAME_ISNOT_ALL_NUMBER, '', []);
        }
        $where['username'] = $this->username;
        if (UserModel::getUserData($where)) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_USERNAME_IS_USERD, '', []);
        }
        if (MemberModel::getUserByUserName($this->username)) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_USERNAME_IS_USERD, '', []);
        }
        return true;
    }

    /**
     * 验证短信验证码
     */
    public function checkSmsCode()
    {
        if (!$this->mobile || !$this->code) {
            throw new ServiceException(ServiceCode::SERVICE_PARAM_INVALID, '', []);
        }
        $codeData = SendCodeModel::checkCode($this->mobile, $this->code);
        if (!$codeData) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_MESSAGE_CODE_IS_ERROR, '', []);
        }
        //验证码的有效期是60分钟
        if ($codeData['created'] + 3600 < time()) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_MESSAGE_CODE_IS_DATED, '', []);
        }
        SendCodeModel::usedCode($this->code, $this->mobile);
        return true;
    }

    /**
     * 验证手机格式
     */
    public function checkMobileFormat($nationCode)
    {
        if ($nationCode == 86) {
            if (!CommFunction::checkMobile($this->mobile)) {
                throw new ServiceException(ServiceCode::SERVICE_OAUTH_MOBILE_FORMAT_IS_WRONG, '', []);
            }
        }
        return true;
    }

    /**
     * 验证手机号码是否被使用
     */
    public function checkMobile()
    {
        $where['mobile'] = $this->mobile;
        if (UserModel::getUserData($where)) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_MOBILE_IS_USERD, '', []);
        }
        return true;
    }

    /**
     * 验证密码格式
     */
    public function checkPasswordFormat()
    {
        $passwordLength = strlen($this->password);
        if ($passwordLength < 6 || $passwordLength > 16) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_PASSWORD_FORMAT_IS_WRONG, '', []);
        }
        return true;
    }

    /**
     * 注册方法
     * $origin注册源；原始来源：0新用户，1通心粉社区，2企业号通讯录，3通威协同业务系统，
     *              4EBS系统，5qq，6新浪微博，7百度，8微信，9账号同步，10fbc系统，
     *              11系统导入，19管理员添加（App管理后台），21快捷登录
     */
    public function regist($origin, $nationCode)
    {
        $data = array();
        $randomKey = CommFunction::makeRandomKey();
        $makePassword = CommFunction::makePassword(trim($this->password), $randomKey);
        $data['password'] = $makePassword;
        $data['key'] = $randomKey;
        $data['mobile'] = $this->mobile;
        $data['username'] = $this->username;
        $data['origin'] = $origin;
        //国际电话区号
        //$data['nationCode'] = $nationCode;
        $data['status'] = UserModel::USER_STATUS_NOMAL;
        $data['created'] = $data['updated'] = time();
        //注册tongwei互联网帐号
        $id = UserModel::addUser($data);
        if ($id) {
            //添加通心粉社区帐号
            $this->addBbsUserAccount($id, $makePassword, $randomKey);
        }
        return $id;
    }

    /**
     * 添加通心粉社区帐号
     */
    public function addBbsUserAccount($id, $makePassword, $key)
    {
        $bbsId = MemberModel::signUp($this->mobile, $makePassword, $this->username, $key);
        if ($id && $bbsId) {
            $data['bbs_uid'] = $bbsId;
            UserModel::updateUser($id, $data);
        }
    }

    /**
     *验证发送验证码的时间间隔
     */
    public function checkSendTime()
    {
        $data = SendCodeModel::getCodeData($this->mobile);
        $sendTime = $data ? $data['created'] : 0;
        if ($sendTime + 60 > time()) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_SENDTIME_IS_SHORT, '', []);
        }
        return true;
    }

    /**
     * 不是公司内网，是公网要做同一个IP地址同一天不超过5次的限制
     */
    public function checkIntranet()
    {
        if (!Environment::isIntranet()) {
            $where[] = ['ip', '=', CommFunction::getip()];
            $where[] = ['year', '=', date('Y', time())];
            $where[] = ['month', '=', date('m', time())];
            $where[] = ['day', '=', date('d', time())];
            $count = SendCodeModel::getCount($where);
            if ($count >= 5) {
                throw new ServiceException(ServiceCode::SERVICE_OAUTH_ONEDAT_REGIST_IS_MORE, '', []);
            }
        }
        return true;
    }

    /**
     * 注册时发送短信验证码
     */
    public function sendSmsCode($nationCode)
    {
        //可以加一步验证验证码操作，这里暂时未实现

        $this->checkMobileFormat($nationCode);
        //发送短信验证码时间间隔验证
        $this->checkSendTime();
        //不是公司内网，是公网要做同一个IP地址同一天不超过5次的限制
        $this->checkIntranet();
        return $this->sendCode($nationCode);
    }

    /**
     * 验证通过后发送短信
     */
    public function sendCode($nationCode)
    {
        $where[] = ['year', '=', date('Y', time())];
        $where[] = ['month', '=', date('m', time())];
        $where[] = ['day', '=', date('d', time())];
        $where[] = ['mobile', '=', $this->mobile];
        $count = SendCodeModel::getCount($where);
        if ($count >= 10) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_SENDCODE_IS_MORE, '', []);
        }
        $code = VerificationCode::getRandCode();
        $content = VerificationCode::getRegistCodeContent($code);
        $result = SmsService::sendMsg($this->mobile, $content, 0, $nationCode);
        if ($result['result'] == 0) {
            //发送验证码成功，保存验证码到数据库
            if (SendCodeModel::addCode($this->mobile, $code)) {
                return true;
            }
        } else {
            //发送短信验证码失败
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_SENDCODE_IS_FAIL, '', $result);
        }

    }

    /**
     * 注册成功后添加用户附加信息(主要是地理信息省，市2个)
     */
    public function addUserProfile($userid)
    {
        $params = CommFunction::getCityByGaoDe();
        if ($params['province']) {
            $region = $params['region'];
            $where[] = ['name', '=', $region];
            $where[] = ['level', '=', 1];
            $result = DistrictModel::getDistrict($where);
            if ($result) {
                $data['province'] = $result['id'];
                unset($result);
                unset($where);
            }
        }
        if ($params['city']) {
            $city = $params['city'];
            $where[] = ['name', '=', $city];
            $where[] = ['level', '=', 2];
            $result = DistrictModel::getDistrict($where);
            if ($result) {
                $data['city'] = $result['id'];
            }
        }
        $data['user_id'] = $userid;
        if (UserProfileModel::addUserProfile($data)) {
            return true;
        }
        return false;
    }

    /**
     * 将用户信息添加到微信企业号
     * 暂时放在微信的 orgid=7058 这个组织中，
     * 因为用户没有对应的真实姓名
     */
    public function addUserInforToWeChat()
    {
        $params['userid'] = $this->mobile;
        $params['name'] = $this->username;
        $params['department'] = WechatConfig::NEW_REGIST_ORG_ID;
        $params['mobile'] = $this->mobile;
        $wechatUserService = new WechatUserService();
        return $wechatUserService->addWechatUser($params);
    }

    /**
     * plus中的用户和微信企业号的用户关联
     * tw_base_user_weixin
     * tw_weixin_user 暂时放到orgId=3585上
     */
    public function plusUserRelateWechatUser($userId, $wechatId, $username)
    {
        //添加到plususer和微信user的中间表中（tw_base_user_weixin）
        $data['user_id'] = $userId;
        $data['wechat_userid'] = $this->mobile;
        $data['created'] = time();
        UserWeiXinModel::addUserWeiXin($data);
        unset($data);
        //添加微信新增用户统计表中（tw_weixin_user）
        $data['userid'] = $this->mobile;;
        $data['username'] = $this->username;
        $data['org_id'] = 3585;
        $data['invitemobile'] = $this->mobile;;
        $data['invitename'] = $this->username;
        $data['userkind'] = 4;
        $data['invitekind'] = 3;
        $data['invitestate'] = 4;
        $data['addtime'] = time();
        $data['origin'] = 'pc';
        //暂时不保存过去
        //WeiXinUserModel::addWeiXinUser($data);
    }


}